package com.jyw.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.hankcs.hanlp.dictionary.py.Pinyin;
import com.hankcs.hanlp.dictionary.py.PinyinDictionary;

import java.util.List;

/**
 * @author Created by ZhangCheng on 2024/01/18 （多音字处理拼音工具类）
 */
public class PinyinUtil {

    /**
     * 获取中文完整拼音
     *
     * @param chineseStr
     * @return
     */
    public static String getPinyin(String chineseStr) {
        List<Pinyin> pinyinList = PinyinDictionary.convertToPinyin(chineseStr);
        StringBuilder stringBuilder = new StringBuilder();
        for (Pinyin pinyin : pinyinList) {
            stringBuilder.append(pinyin.getPinyinWithoutTone());
        }
        return stringBuilder.toString();
    }


    /**
     * 获取中文拼音首字母
     *
     * @param chineseStr
     * @return
     */
    public static String getFirstLetter(String chineseStr) {
        List<Pinyin> pinyinList = PinyinDictionary.convertToPinyin(chineseStr);
        if (CollUtil.isEmpty(pinyinList)) {
            return StrUtil.EMPTY;
        }
        return CollUtil.join(pinyinList, "", (s)->String.valueOf(s.getPinyinWithoutTone().length() > 0 ? s.getPinyinWithoutTone().charAt(0) : StrUtil.EMPTY));
    }
}
